package de.pixel83.piecemaster.ai;

import java.util.ArrayList;

import de.pixel83.piecemaster.Board;
import de.pixel83.piecemaster.Move;
import de.pixel83.piecemaster.Square;

public class RandomAi implements Ai {

	public String getName() {
		return "RandomAi";
	}

	public Move draw(Board board, char color) {
		Square start = null;
		Move move = null;

		while (move == null) {
			ArrayList<Square> ownPieces = getAllPieces(board, color);
			double rand = Math.random();
			double m = rand * ownPieces.size();
			int squareNo = (int) Math.floor(m);
			start = ownPieces.get(squareNo);

			assert (start != null);

			ArrayList<Move> legalMoves = board.getLegalMoves(start);
			if (legalMoves.size() > 0) {
				int itemNo = (int) Math.round(Math.random()
						* (legalMoves.size() - 1));
				move = legalMoves.get(itemNo);
			} else {
				start = null;
			}
		}
		return move;
	}

	private ArrayList<Square> getAllPieces(Board board, char color) {
		ArrayList<Square> list = new ArrayList<Square>();
		for (int r = 0; r < 6; r++) {
			for (int c = 0; c < 5; c++) {
				if (board.getColor(board.getPieceAt(r, c)) == color) {
					list.add(new Square(c, r));
				}
			}
		}
		return list;
	}

	/**
	 * Tests the class RandomAi
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		Board board = new Board();
		Ai ai = new RandomAi();
		for (int i = 0; i < 3; i++)
			System.out.println(ai.draw(board, 'W'));
	}

}
